package com.wzx.filter;
import com.wzx.pojo.LoginAdmin;
import com.wzx.pojo.LoginUser;
import com.wzx.utils.JwtUtil;
import com.wzx.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Value("${JWT.userLogin}")
    private String userLogin;
    @Value("${JWT.adminLogin}")
    private String adminLogin;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();

        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }
        UserDetails userDetails = null;
        if (request.getRequestURI().startsWith("/user/")){
            String redisKey = userLogin + userId;
            userDetails = redisCache.getCacheObject(redisKey);
        }else if (request.getRequestURI().startsWith("/admin/")){
            String redisKey2 = adminLogin + userId;
            userDetails = redisCache.getCacheObject(redisKey2);
        }
        if (Objects.isNull(userDetails)){
            throw new RuntimeException("用户未登录!");
        }
        //TODO 最后一个参数是权限信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
